package uk.co.biggroup.lotto.syndicate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.client.ClientProtocolException;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import org.xml.sax.SAXException;

import uk.co.biggroup.lotto.syndicate.dataset.DataDraw;
import uk.co.biggroup.lotto.syndicate.dataset.DataDraws;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Draws extends ListActivity {

	public static final String PREFS_NAME = "Settings";
	public static int error;
	TextView tlastupdate;
	TextView tbalance;
	TextView tstatus;
	DataDraws dataset;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.draws);
		tstatus = (TextView) this.findViewById(R.id.status);
		tbalance = (TextView) this.findViewById(R.id.balance);
		tlastupdate = (TextView) this.findViewById(R.id.lastupdate);

		// System.currentTimeMillis();
		// deleteFile("BIGSyndicateData.bin");

		dataset = (DataDraws) LocalPersistence.readObjectFromFile(Draws.this,
				"BIGSyndicateData.bin");
		if (dataset == null) {
			new DownloadGroups().execute("");
		} else {
			this.presentResults();
		}

	}

	public void onListItemClick(ListView parent, View v, int position, long id) {
		final Bundle bundle = new Bundle();
		bundle.putInt("drawid", position);
		bundle.putSerializable("DataSet", dataset);
		Logh.i("JHubsList button pressed");
		Intent myIntents = new Intent(parent.getContext(), Numbers.class);
		myIntents.putExtras(bundle);
		startActivityForResult(myIntents, 311);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(1, 2, 1, "Refresh").setIcon(R.drawable.ic_menu_refresh);
		return super.onCreateOptionsMenu(menu);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 2:
			new DownloadGroups().execute("");
			break;
		}
		return true;
	}

	public void presentResults() {
		tstatus.setText(dataset.getShortStatus());
		tbalance.setText(dataset.getBalance() + " ");
		tlastupdate.setText(dataset.getUpdated() + " ");

		this.setListAdapter(new IconicAdapter(Draws.this, R.layout.drawitem,
				dataset.getDataDraw()));
	}

	class IconicAdapter extends ArrayAdapter<DataDraw> {

		private ArrayList<DataDraw> items;

		IconicAdapter(Context context, int textViewResourceId,
				ArrayList<DataDraw> itemsyx) {
			super(context, textViewResourceId, itemsyx);
			this.items = itemsyx;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = getLayoutInflater();
			View drawitem = inflater.inflate(R.layout.drawitem, parent, false);
			TextView date = (TextView) drawitem.findViewById(R.id.date);
			TextView status = (TextView) drawitem.findViewById(R.id.status);
			TextView result = (TextView) drawitem.findViewById(R.id.result);
			ImageView icon = (ImageView) drawitem.findViewById(R.id.icon);
			DataDraw d = items.get(position);
			if (d != null) {
				date.setText(d.getDate());
				status.setText(d.getStatus());
				result.setText(d.getResult());
				if (d.getType() == 3) {
					icon.setImageResource(R.drawable.health_logoballsm);
				} else if (d.getType() == 2) {
					icon.setImageResource(R.drawable.euro_logoballsm);
				} else if (d.getType() == 1) {
					icon.setImageResource(R.drawable.lotto_logoballsm);
				} else {
					icon.setImageResource(R.drawable.lotto_logoballsm);
				}
			}
			return (drawitem);
		}
	}

	private class DownloadGroups extends AsyncTask<String, Void, String> {

		ProgressDialog dialog;

		@Override
		protected String doInBackground(String... params) {
			error = 0;
			try {
				getHtml();
			} catch (ClientProtocolException e) {
				Logh.i("ClientProtocolException");
			} catch (IOException e) {
				error = 1;
				Logh.i("IOException");
			} catch (XPatherException e) {
				Logh.i("XPatherException");
			} catch (ParserConfigurationException e) {
				Logh.i("ParserConfigurationException");
			} catch (SAXException e) {
				Logh.i("SAXException");
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			dialog.dismiss();

			if (error == 1) {
				if (dataset == null) {
					Intent intent = new Intent();
					intent.setClass(Draws.this, Welcome.class);
					startActivity(intent);
					finish();
				} else {
					Toast.makeText(Draws.this,
							"Sorry! There is no connection. Try again later.",
							Toast.LENGTH_LONG).show();
				}
			}

			Draws.this.presentResults();

		}

		@Override
		protected void onPreExecute() {
			dialog = ProgressDialog.show(Draws.this, "",
					"Wait, Accessing data...", true);
		}

		@Override
		protected void onProgressUpdate(Void... values) {

		}

		public void getHtml() throws ClientProtocolException, IOException,
				XPatherException, ParserConfigurationException, SAXException,
				IOException, XPatherException {

			TagNode node;

			SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
			String tokenCheck = settings.getString("token", "");

			URL url = new URL(
					"http://syndicates.biggroup.co.uk/MyAccount/DownloadXML.aspx?t="
							+ tokenCheck);
			URLConnection conn = url.openConnection();

			HtmlCleaner cleaner = new HtmlCleaner();
			CleanerProperties props = cleaner.getProperties();
			props.setAllowHtmlInsideAttributes(true);
			props.setAllowMultiWordAttributes(true);
			props.setRecognizeUnicodeChars(true);
			props.setTranslateSpecialEntities(true);
			props.setOmitComments(true);

			node = cleaner.clean(new InputStreamReader(conn.getInputStream()));

			dataset = new DataDraws(node);
			LocalPersistence.witeObjectToFile(Draws.this, dataset,
					"BIGSyndicateData.bin");
			// SAVE TIME HERE TO SharedPreferences
		}
	}
}
